<?php

namespace app\index\service;

use think\Db;
use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\index\model\UserModel;
use app\index\model\NewproductauditModel;
use app\index\service\DatamanufactureService;

class NewproductauditService
{
    /**
     * 资料包/样品列表导出
     * @author LSH
     * @return array
     */
    public static function getManufactureList($param){

        $titles = [
            'sku'=>'sku',
            'spu'=>'spu',
            'name'=>'采购名称'
        ];

        if(isset($param['type']) && $param['type'] == 2){
            $titles['develop_remarks'] = '开发备注';
            $titles['developer'] = '开发人员';
            $titles['imitation'] = '仿品（具体品牌）';
            $titles['realpic'] = '盗图/实拍图';
            $titles['logo'] = '品牌Logo';
            $titles['quantityunit'] = '销售数量/单位';
            $titles['production_type_num'] = '样品数量';
            $titles['authorization_name'] = '是否授权';
            $titles['type'] = '交接类型';
            $titles['sample_status_name'] = '样品状态';
            $titles['return_people'] = '归还人';
            $titles['return_time'] = '归还时间';
            $titles['img_grade'] = '图片等级';
            $titles['status_name'] = '审核状态';
            $titles['auditor'] = '审核人';
            $titles['audit_time'] = '审核时间';
            $titles['audit_remarks'] = '审核备注';
        }else{
            $titles['creation_time'] = '交接时间';
            $titles['developer'] = '开发人员';
            $titles['imitation'] = '仿品（具体品牌）';
            $titles['realpic'] = '盗图/实拍图';
            $titles['logo'] = '品牌Logo';
            $titles['quantityunit'] = '销售数量/单位';
            $titles['develop_link'] = '开发链接';
            $titles['research_links'] = '调研链接';
            $titles['type'] = '交接类型';
            $titles['authorization_name'] = '是否授权';
            $titles['aslengthaswideashight'] = '打包前尺寸';
            $titles['develop_remarks'] = '交接备注'; 
            $titles['img_grade'] = '图片等级';
            $titles['status_name'] = '审核状态';
            $titles['auditor'] = '审核人';
            $titles['audit_time'] = '审核时间';
            $titles['remarks'] = '审核备注';           
        }

        return NewproductauditModel::dbGetManufactureList($param, $titles, "\app\index\service\NewproductauditService::getManufactureListLogic");
    }

    /**
     * 资料包/样品列表数据逻辑
     * @author LSH
     * @return array
     */
    public static function getManufactureListLogic($data){
        $butt_man = array_column($data, 'butt_man');
        $auditor = array_column($data, 'auditor');
        $return_people = array_column($data, 'return_people');
        $developer = array_column($data, 'developer');
        $user_id = array_merge($butt_man,$auditor,$return_people,$developer);

        $user = UserModel::getUserById($user_id);
        foreach ($data as &$val) {
            $val['butt_man'] = $user[$val['butt_man']]??'';
            $val['auditor'] = $user[$val['auditor']]??'';
            $val['return_people'] = $user[$val['return_people']]??'';
            $val['developer'] = $user[$val['developer']]??'';
            $val['quantityunit'] = $val['quantity'].$val['quantity_unit'];
            $val['aslengthaswideashight'] = $val['aslength'].'*'.$val['aswide'].'*'.$val['ashight'];
        }
        return $data;
    }

    /**
     * 资料包/样品导入
     * @author LSH
     * @return array
     */
    public static function uploadManufactureListInfo($datas, $param)
    {
        $error = [];
        $auditStatus = ['通过'=>2,'驳回'=>3];
        $skus = ToolModel::select('manage_manufacture_audit', ['sku'=>['IN',array_column($datas, '0')]], '*','','sku');
        //原 sku 图片等级    审核状态    审核备注
        //新(资料包) sku spu 采购名称    交接时间    开发人员    仿品（具体品牌）    盗图/实拍图  品牌Logo  销售数量/单位 开发链接    调研链接    交接类型    是否授权    打包前尺寸   交接备注    图片等级    审核状态    审核人 审核时间    审核备注
        //新(样品) sku   spu 采购名称    开发备注    开发人员    仿品（具体品牌）    盗图/实拍图  品牌Logo  销售数量/单位 样品数量    是否授权    交接类型    样品状态    归还人 归还时间    图片等级    审核状态    审核人 审核时间    审核备注
        //只是保持格式，方便业务人员操作，原数据 才是用到的数据
        foreach ($datas as $v) {
            $data = [];
            $sku = $v[0];
            $grade = $v[15];
            $status = $auditStatus[$v[16]]??'';
            $remark = $v[19];
          
            if (!isset($skus[$sku])) {
                $error[] = "SKU: {$sku} 不存在!  ";
                continue;
            }

            if (isset($skus[$sku]['status']) && $skus[$sku]['status'] == 2) {
                $error[] = "SKU: {$sku} 已审核，请勿重复操作!  ";
                continue;
            }

            if(empty($status)){
                $error[] = "SKU: {$sku} 状态只能是 通过或驳回  ";
                continue;
            }

            $data['sku'] = $sku;
            $data['status'] = $status;
            $data['remarks'] = $remark;
            $data['grade'] = $grade;
            $data['import'] = 1;
            if(!NewproductauditModel::dbUpdateManufactureAudit($data,$param['uid'])){
                $error[] = "SKU: {$sku} 审核失败!  ";
                continue; 
            }
        }
        
        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            $code = (count($datas) == count($error))?2:4;
            unset($datas,$data,$error);
            return returnArr($code, '',$msg);
        }
         unset($datas,$data);
        //成功
        return returnArr();
    }

    /**
     * 新品分派列表 导出
     * @author LSH
     * @return array
     */
    public static function getNewProductAssignList($param){
        $titles = [
            'sku'=>'sku',
            'spu'=>'spu',
            'name'=>'采购名称',
            'creation_time'=>'交接时间',
            'developer_name'=>'开发人员',
            'imitation'=>'仿品（具体品牌）',
            'realpic'=>'盗图/实拍图',
            'logo'=>'品牌Logo',
            'quantityunit'=>'销售数量/单位',
            'develop_link'=>'开发链接',
            'research_links'=>'调研链接',
            'handover_type'=>'交接类型',
            'authorization_name'=>'是否授权',
            'aslengthaswideashight'=>'打包前尺寸',
            'develop_remarks'=>'交接备注',
            'production_type_name'=>'制作类型',
            'edit_grade'=>'描述等级',
            'edit_operator_name'=>'编辑人员',
            'img_grade'=>'图片等级',
            'img_operator_name'=>'图片人员',
            'assign_status_name'=>'状态',
        ];

        return NewproductauditModel::dbGetNewProductAssignInfo($param, $titles, "\app\index\service\NewproductauditService::getNewProductAssignLogic");
    }

    /**
     * 新品数据逻辑
     * @author LSH
     * @return array
     */
    public static function getNewProductAssignLogic($data){
        $img_operator = array_column($data, 'img_operator');
        $edit_operator = array_column($data, 'edit_operator');
        $developer = array_column($data, 'developer');
        $user_id = array_filter(array_merge($img_operator,$edit_operator,$developer));

        $user = UserModel::getUserById($user_id);
        foreach ($data as &$val) {
            $val['img_operator_name'] = $user[$val['img_operator']]??'';
            $val['edit_operator_name'] = $user[$val['edit_operator']]??'';
            $val['developer_name'] = $user[$val['developer']]??'';
            $val['quantityunit'] = $val['quantity'].$val['quantity_unit'];
            $val['aslengthaswideashight'] = $val['aslength'].'*'.$val['aswide'].'*'.$val['ashight'];
            $val['img_assign_time'] = $val['img_assign_time']=='0000-00-00 00:00:00'?'':$val['img_assign_time'];
            $val['edit_assign_time'] = $val['edit_assign_time']=='0000-00-00 00:00:00'?'':$val['edit_assign_time'];
        }

        return $data;
    }

    /**
     * 新品分派导入
     * @author LSH
     * @return array
     */
    public static function uploadSampleListInfo($datas, $param)
    {   
        $i = 0;
        $error = [];
        $newProductAssignStatus = array_flip(ConfigBase::$newProductAssignStatus);
        $img_operators = array_column($datas, '19');
        $edit_operators = array_column($datas, '17');
        $user_name = array_unique(array_filter(array_merge($img_operators,$edit_operators)));

        $user = UserModel::getUserByNike($user_name);
        $assign_all = ToolModel::select('manage_assign', ['sku'=>['IN',array_column($datas, '0')]], '*','','sku');

        //原 sku、描述等级 、状态、图片人员、编辑人员
        //新 sku spu 采购名称    交接时间    开发人员    仿品（具体品牌）    盗图/实拍图  品牌Logo  销售数量/单位 开发链接    调研链接    交接类型    是否授权    打包前尺寸   交接备注    制作类型    描述等级    编辑人员    图片等级    图片人员    状态
        //只是保持格式，方便业务人员操作，原数据 才是用到的数据
        foreach ($datas as $v) {
            $markimg = $markedit = true;
            $assign = [];
            $sku = $v[0];
            $edit_grade = $v[16]; //描述等级

            //图片等级迁移到资料包/样品审核  不允许后期二次更改
            // $img_grade = $v[2]; //图片等级
            $editoper = $v[17];
            $imgoper = $v[19];
            $statusname = $v[20];

            $status = $newProductAssignStatus[$statusname]??''; //状态
            $img_operator = $user[$imgoper]??''; //图片人员
            $edit_operator = $user[$editoper]??''; //编辑人员

            $assign_d = $assign_all[$sku]??'';
            if (empty($assign_d)) {
                $error[] = "SKU: {$sku} 不存在。 ";
                continue;
            }

            if ($assign_d['assign_status'] == 2) {
                $error[] = "SKU: {$sku} 已分派!  ";
                continue;
            }

            !empty($edit_grade)&&$assign['edit_grade'] = $edit_grade;
            // !empty($img_grade)&&$assign['img_grade'] = $img_grade;

            if(trim($statusname)){
                if(empty($status)){
                    $error[] = "SKU: {$sku}状态只能是 待分派或已分派  ";
                    continue;
                }
                $assign['assign_status'] = $status;
            }

            if(trim($imgoper)){
                if(!empty($assign_d['img_operator'])){
                    $error[] = "SKU: {$sku} 图片人员已分派!  ";
                    $markimg = false;
                }else if(empty($img_operator)){
                    $error[] = "SKU: {$sku} 图片人员 {$imgoper} 不存在!  ";
                    continue;
                }

                if($markimg) $assign['img_operator'] = $img_operator;
            }

            if(trim($editoper)){
                if(!empty($assign_d['edit_operator'])){
                    $error[] = "SKU: {$sku} 编辑人员已分派!  ";
                    $markedit = false;
                }else if(empty($edit_operator)){
                    $error[] = "SKU: {$sku} 编辑人员 {$editoper} 不存在!  ";
                    continue;
                }
                if($markedit) $assign['edit_operator'] = $edit_operator;
            }

            if($status == 2){
                if(!($assign_d['img_operator']||$img_operator)&&($assign_d['edit_operator']||$edit_operator)){
                    $error[] = "SKU: {$sku} 按业务要求，编辑分派人员后，必须等待图片分派人员才可以更改状态为已分派。";
                    continue; 
                }
            }
            
            if($markimg == false && $markedit == false) continue;

            Db::startTrans();
            try{

                //导入 后期更改分派状态
                if(!trim($editoper) && !trim($imgoper) && $status == 2 && !empty($assign_d['img_operator']) && empty($assign_d['edit_operator'])){
                    Db::table('manage_assign')
                        ->where('sku',$sku)
                        ->update(['assign_status'=>2,'assign_time'=>date('Y-m-d H:i:s',time()),'assign_operator'=>$param['uid']]);
                    //如果审核通过，把交接状态更改为已完成
                    $m_status = Db::table('manage_img_audit')->where('sku',$sku)->value('manufacture_status');
                    if($m_status == 5){
                        Db::table('sku_handover')
                            ->where('sku',$sku)
                            ->update(['status'=>5,'modification_time'=>date('Y-m-d H:i:s',time()),'modification_operator'=>$param['cn_name']]);
                    }
                }else{

                    if(empty($assign)){
                        $error[] = "SKU: {$sku} 无更改信息!  ";
                        continue;
                    }

                    if(($assign_d['img_operator']||$img_operator)&&($assign_d['edit_operator']||$edit_operator)){
                        $assign['assign_status'] = 2;
                    }

                    if(isset($assign['assign_status']) && $assign['assign_status'] == 2){
                        $assign['assign_time'] = date('Y-m-d H:i:s',time());
                        $assign['assign_operator'] = $param['uid'];
                    }

                    $data = [];
                    $data['sku'] = $sku;
                    $data['manufacture_status'] = 2;
                    $data['assign_id'] = $assign_d['id'];
                    $data['import_operator'] = $param['uid'];
                    $data['assign_time'] = date('Y-m-d H:i:s',time());
                    
                    $editor = [];
                    $editor[0]['sku'] = $sku;
                    $editor[0]['spu'] = Db::table('skus')->where('sku',$sku)->value('spu');
                    $editor[0]['operator'] = $param['uid'];
                    $editor[0]['update_time'] = date('Y-m-d H:i:s',time());
                    if($img_operator && $markimg){
                        $i++;
                        $data['grade'] = $assign_d['img_grade'];
                        $data['operator'] = $assign['img_operator'];
                        Db::table('manage_img_audit')->insert($data);

                        $editor[0]['img_operator'] = $assign['img_operator'];
                        $assign['img_assign_time'] = date('Y-m-d H:i:s',time());
                        $assign['img_assign_operator'] = $param['uid'];               
                    }

                    if($edit_operator && $markedit){
                        $i++;
                        $data['grade'] = $assign['edit_grade']??'';
                        $data['operator'] = $assign['edit_operator'];
                        Db::table('manage_edit_audit')->insert($data); 

                        $editor[0]['edit_operator'] = $assign['edit_operator'];     
                        $assign['edit_assign_time'] = date('Y-m-d H:i:s',time());
                        $assign['edit_assign_operator'] = $param['uid'];                   
                    }

                    ToolModel::dbInsertOrUpdate('setting_editor', $editor);
                    Db::table('manage_assign')->where('sku',$sku)->update($assign);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $error[] = "SKU: {$sku} 操作失败！".$e->getMessage();
                continue;
            }
        }
        
        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            $code = (count($datas) == count($error))?2:4;
            if($code == 2 && $i) $code = 4;
            unset($datas,$data,$error);
            return returnArr($code, '',$msg);
        }
        unset($datas,$data);
        //成功
        return returnArr();
    }

    /**
     * 编辑/图片审核列表 导出
     * @author LSH
     * @return array
     */
    public static function getEditImgAuditList($param){
        $titles=[
            'sku'=>'sku',
            'spu'=>'spu',
            'name'=>'采购名称',
            'handover_type'=>'交接类型'
        ];

        if($param['type'] == 'edit'){
            $titles['imitation']='仿品（具体品牌）';
            $titles['realpic']='盗图/实拍图';
            $titles['logo']='品牌Logo';
            $titles['quantity']='销售数量/单位';
            $titles['develop_link']='开发链接';
            $titles['research_links']='调研链接';
            $titles['hauthorization']='是否授权';
            $titles['aslengthaswideashight']='打包前尺寸';
            $titles['handover_remarks']='交接备注';
            $titles['production_type']='制作类型';
            $titles['developer']='开发人员';
            $titles['grade']='描述等级';
            $titles['operator']='编辑人员';
            $titles['audit_status']='审核状态';
            $titles['auditor']='审核人';
            $titles['audit_time']='审核时间';
            $titles['haudit_remarks']='审核备注';
            $titles['title_template']='标题';
            $titles['desc_template']='描述';
            $titles['color']='color';
            $titles['type']='type';
            $titles['shape']='shape';
            $titles['size']='size';
            $titles['pattern']='pattern';
        }else if($param['type'] == 'img'){
            $titles['imitation']='仿品（具体品牌）';
            $titles['realpic']='盗图/实拍图';
            $titles['logo']='品牌Logo';
            $titles['quantity']='销售数量/单位';
            $titles['develop_link']='开发链接';
            $titles['research_links']='调研链接';
            $titles['authorization']='是否授权';
            $titles['aslengthaswideashight']='打包前尺寸';
            $titles['handover_remarks']='交接备注';
            $titles['production_type']='制作类型';
            $titles['developer']='开发人员';
            $titles['grade']='图片等级';
            $titles['operator']='图片人员';
            $titles['finish_time']='图片完成时间';
            $titles['audit_status']='审核状态';

        }

        return NewproductauditModel::dbGetEditImgAuditList($param, $titles, "\app\index\service\NewproductauditService::getEditImgAuditListLogic");
    }

    /**
     * 编辑审核列表数据逻辑
     * @author LSH
     * @return array
     */
    public static function getEditImgAuditListLogic($data){
        $developer = array_column($data, 'developer');
        $operator = array_column($data, 'operator');
        $auditor = array_column($data, 'auditor');
        $user_id = array_filter(array_merge($developer,$operator,$auditor));

        if(isset($data[0]) && $data[0]['ttype'] == 'img'){
            $sku_arr = array_column($data, 'sku');
            $img = DatamanufactureService::getSkuImgBatch($sku_arr);
        }

        $user = UserModel::getUserById($user_id);
        foreach ($data as &$val) {
            $val['quantity'] = $val['hquantity'].$val['hquantity_unit'];
            $val['developer'] = $user[$val['developer']]??'';
            $val['operator'] = $user[$val['operator']]??'';
            $val['auditor'] = $user[$val['auditor']]??'';
            $val['aslengthaswideashight'] = $val['aslength'].'*'.$val['aswide'].'*'.$val['ashight'];

            if(isset($val['desc_template'])){
                $description = '';
                $descArr = json_decode($val['desc_template'],TRUE);
                if(is_array($descArr) && !empty($descArr)){
                    foreach ($descArr as $dkey => $dval) {
                        $description .= $dkey.'：'.$dval.'    ';
                    }
                }
                $val['desc_template'] = htmlspecialchars_decode($description);
            }
            
            if(isset($val['title_template'])){
                $title = '';
                $titleArr = json_decode($val['title_template'],TRUE);
                if(isset($titleArr['value']) && is_array($titleArr['value']) && !empty($titleArr['value'])){
                    foreach ($titleArr['value'] as $tval) {
                        $title .= str_replace('卍','、',$tval).'  ';
                    }
                }
                $val['title_template'] = $title;
            }
            if($val['ttype'] == 'img') $val['img'] = $img[$val['sku']]??'';
        }

        return $data;
    }

    /**
     * 编辑/图片审核导入
     * @author LSH
     * @return array
     */
    public static function uploadEditImgAuditInfo($datas, $param)
    {
        $error = [];
        $auditStatus = ['通过'=>2,'驳回'=>3];
        $table = ($param['type'] == 'edit')?'manage_edit_audit':'manage_img_audit';
        $where = ['sku'=>['IN',array_column($datas, '0')],'audit_status'=>['<>','2'],'cancel'=>0,'assign_id'=>['>',0]];
        $skus = ToolModel::select($table, $where, '*','','sku');

        // sku、审核状态、审核备注 
        foreach ($datas as $v) {
            $data = [];
            $sku = $v[0];
            $status = $auditStatus[$v[1]]??''; //审核状态
            $remarks = $v[2]; //审核备注
          
            if (!isset($skus[$sku])) {
                $error[] = "SKU: {$sku} 不存在或已审核!  ";
                continue;
            }

            if(empty($status)){
                $error[] = "SKU: {$sku} 审核状态 {$v[1]} 不存在!  ";
                continue;
            }

            $data['sku'] = $sku;
            $data['id'] = $skus[$sku]['id'];
            $data['type'] = $param['type'];
            $data['status'] = $status;
            $data['remarks'] = $remarks;
            if($param['type'] == 'edit' && $status == 2){
                $field = ['color','type','shape','size','pattern','title_template','desc_template','smt_template'];
                foreach ($field as $val) {
                    $data['fd'.$val] = $skus[$sku][$val];
                }
            }

            if(!NewproductauditModel::dbUpdateMaterialAudit($data,$param['uid'])){
                $error[] = "SKU: {$sku} 审核失败!  ";
                continue;
            }
        }
        
        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            $code = (count($datas) == count($error))?2:4;
            unset($datas,$data,$error);
            return returnArr($code, '',$msg);
        }
        unset($datas,$data);
        //成功
        return returnArr();
    }

    /**
     * 新品 图片/描述分派
     * @author LSH
     * @return array
     */
    public static function insertAssignInfoLogic($param){
        if(empty($param['id']) || empty($param['sku'])){
            return returnJson(0,'参数错误');
        }

        $data = ToolModel::find('manage_assign', ['id'=>$param['id']]);
        if(empty($data)){
            return returnJson(0,'数据不存在');
        }

        if(empty($data['sku'])){
            return returnJson(0,'参数缺失');
        }

        if(!empty($data[$param['type'].'_operator'])){
            return returnJson(0,'此数据已分派,请勿重复操作');
        }

        return NewproductauditModel::insertAssignInfo($param,$data);
    }

    /**
     * 样品归还
     * @author LSH
     * @return array
     */
    public static function updateSampleReturnLogic($param){
        if(empty($param['id'])){
            return returnJson(0,'参数错误');
        }
        $data = ToolModel::select('manage_manufacture_audit',['id'=>$param['id']]);
        if(empty($data)){
            return returnJson(0,'数据不存在');
        }

        return NewproductauditModel::dbUpdateSampleReturn($param);
    }


    /**
     * 图片/编辑 审核数据
     * @author LSH
     * @return array
     */
    public static function updateMaterialAuditLogic($param){
        if(empty($param['id'])){
            return returnJson(0,'参数错误');
        }

        if($param['type'] == 'edit')
            $table = 'manage_edit_audit';
        else if($param['type'] == 'img')
            $table = 'manage_img_audit';
        
        $data = ToolModel::find($table,['id'=>$param['id']]);
        if(empty($data['sku'])){
            return returnJson(0,'数据不存在');
        }
        if(!in_array($data['audit_status'], [1,3])){
            return returnJson(0,'数据已审核,请勿重复操作');
        }

        $param['sku'] = $data['sku'];
        if($param['status'] == 2 && $param['type'] == 'edit'){
            $field = ['color','type','shape','size','pattern','title_template','desc_template','smt_template'];
            foreach ($field as $val) {
                $param['fd'.$val] = $data[$val];
            }
        }

        return NewproductauditModel::dbUpdateMaterialAudit($param,UID);
    }

    /**
     * 资料包/样品 审核数据
     * @author LSH
     * @return array
     */
    public static function updateManufactureAuditLogic($param){
        if(empty($param['id'])){
            return returnJson(0,'参数错误');
        }
        $data = ToolModel::find('manage_manufacture_audit',['id'=>$param['id'],'sku'=>$param['sku']]);
        if(empty($data)){
            return returnJson(0,'数据不存在');
        }
        if(empty($data['sku'])){
            return returnJson(0,'参数缺失');
        }
        if($data['status'] != 1){
            return returnJson(0,'此数据已审核，请勿重复操作！');
        }
        return NewproductauditModel::dbUpdateManufactureAudit($param,UID);
    }
    //打回到交接
    public static function deleteAudit($data, $param){
        $aSkus=array_column($data, '0');
        $nSku=Db::table('sku_handover')->where([
            'sku'=>['in',$aSkus],'status'=>['in',[4,5]]
        ])->column('sku',null);
        $skus=array_diff($aSkus,$nSku);
        if(empty($skus)){
            return returnArr();
        }
        Db::table('manage_edit_audit')->where([
            'sku'=>['in',$skus]
        ])->delete();
        Db::table('manage_img_audit')->where([
            'sku'=>['in',$skus]
        ])->delete();
        Db::table('manage_assign')->where([
            'sku'=>['in',$skus]
        ])->delete();
        Db::table('manage_manufacture_audit')->where([
            'sku'=>['in',$skus]
        ])->update(
            ['status'=>1]
        );
        Db::table('sku_handover')->where([
            'sku'=>['in',$skus]
        ])->update(
            ['status'=>1]
        );
        return returnArr();
    }
}